#encoding=utf-8
'''
Created on 2018-7-29

@author: cooler
'''
import sys,os
import random,string
import hashlib
import logging
import time
from cryptography.fernet import Fernet #加密解密模块


logger = logging.getLogger('utils')

PWD_KEY = "suface$#@.$sdsa"

def getMd5Value(src):
    myMd5 = hashlib.md5()
    myMd5.update(src.encode("utf8"))
    myMd5_Digest = myMd5.hexdigest()
    return myMd5_Digest

def init_salt():
    salt = Fernet.generate_key()
    salt = salt.decode()
    return salt

def init_api_key():
    salt = Fernet.generate_key()
    salt = salt.decode()
    return salt
    
def init_secret_key():
    salt = Fernet.generate_key()
    salt = salt.decode()
    return salt

def init_password(password,salt):
    pwd1 = getMd5Value(password+PWD_KEY).lower()
    pwd2 = getMd5Value(pwd1+salt).lower()
    return pwd2

def checkPhone(phone):
    if len(phone) == 11:
        try:
            for x in phone:
                n = int(x)
            return True
        except Exception as e:
            return False
    else:
        return False

def encodeData(salt,data_str):
    salt = salt.encode(encoding="utf-8")
    cipher = Fernet(salt)
    data_str = cipher.encrypt(data_str.encode(encoding="utf-8")+PWD_KEY).decode()
    return data_str

def decodeData(salt,data_str):
    salt = salt.encode(encoding="utf-8")
    cipher = Fernet(salt)
    data_str = cipher.decrypt(data_str.encode(encoding="utf-8")).decode()[:-len(PWD_KEY)]
    return data_str

def checkSign(args):
    flag = True
    try:    
        if args == None:
            logger.info("args is None")
        else:
            sign = str(args.get("sign",""))
            # logger.info("sign:"+sign)
            sortList = sorted(args.items(), key=lambda d:d[0])
            bufstr = ""
            for s in sortList:
                key = str(s[0])
                val = str(s[1])
                # logger.info("key:"+key+",val:"+val)
                if key =="sign":
                    pass
                else:
                    bufstr += key+"="+val
            bufstrmd5 = getMd5Value(bufstr).upper()
            bufstrmd5second = getMd5Value(bufstrmd5+"0S+25d;asdf62.A891,ofo|ofo").upper()
            # logger.info(bufstr)
            # logger.info(bufstrmd5)
            # logger.info(bufstrmd5+"0S+25d;asdf62.A891,ofo|ofo")
            # logger.info("sign:"+bufstrmd5second)
            if sign == bufstrmd5second:
                pass
            else:
                flag = False
    except Exception as e:
        logger.info(str(e))
        flag = False
    return flag

if __name__ == '__main__':
    salt =  get_salt()
    print salt
    print init_password("cooler",salt)